﻿using FineUI;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using Think.Controls;
using Think.Data;
using Think.Model;
using Think.Permission;
using Think.Permission.Model;
using Think.Utils;
using Think.Utils.Web;

namespace Think.Web.App_Code
{
    /// <summary>
    /// 管理员基类
    /// </summary>
    public class AdminPage : System.Web.UI.Page
    {
        #region 属性

        /// <summary>
        /// 管理员登陆名
        /// </summary>
        public AdminUser AdminLoginUser { get; set; }
        /// <summary>
        /// 页面编号
        /// </summary>
        public int PageID { get; set; }
        /// <summary>
        /// 页面URL
        /// </summary>
        public string PageUrl { get; set; }
        /// <summary>
        /// 页面上的操作
        /// </summary>
        public string PageAction = "?Action=";
        /// <summary>
        /// 请求ID
        /// </summary>
        public string ActionID { get; set; }

        #endregion

        #region 页面周期

        protected override void OnPreLoad(EventArgs e)
        {
            base.OnPreLoad(e);

            if (Session["AdminUser"] == null)
            {
                Response.Redirect("/Admin/Login.aspx");
            }
            else
            {
                AdminLoginUser = (AdminUser)Session["AdminUser"];
                PageUrl = RequestUtil.GetUrlNoQueryString();
                PageID = RequestUtil.GetQueryInt("PageID");

                //检查页面权限
                //if (!Manage.CheckPagePermission(AdminLoginUser.LoginName, PageUrl))
                //{
                //    return;
                //}
            }
        }

        #endregion

        #region 通用方法

        #region 获取Grid中选中的值

        /// <summary>
        /// 返回datatable里的主键集合
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetSelectedIDs(DataTable dt, string key)
        {
            string idOld = string.Empty;
            foreach (DataRow row in dt.Rows)
            {
                idOld += row[key].ToString() + ",";
            }
            if (dt.Rows.Count > 0) idOld = idOld.Substring(0, idOld.Length - 1);
            return idOld;
        }

        /// <summary>
        /// 获取表格选中项DataKeys的第一个值，并转化为整型列表
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        protected List<string> GetSelectedDataKeyIDs(FineUI.Grid grid, bool IsEdit)
        {
            List<string> ids = new List<string>();
            if (IsEdit)
            {
                FineUI.CheckBoxField Check = grid.FindColumn("check") as FineUI.CheckBoxField;
                for (int i = 0; i < grid.Rows.Count; i++)
                {
                    if (Check.GetCheckedState(i))
                    {
                        ids.Add(grid.DataKeys[i][0].ToString());
                    }
                }
            }
            else
            {
                foreach (int rowIndex in grid.SelectedRowIndexArray)
                {
                    ids.Add(grid.DataKeys[rowIndex][0].ToString());
                }
            }
            return ids;
        }

        private List<string> GetSelectedRowIndexArrayFromHiddenField(FineUI.HiddenField hfSelectedIDS)
        {
            JArray idsArray = new JArray();
            string currentIDS = hfSelectedIDS.Text.Trim();
            if (!String.IsNullOrEmpty(currentIDS))
            {
                idsArray = JArray.Parse(currentIDS);
            }
            else
            {
                idsArray = new JArray();
            }
            return new List<string>(idsArray.ToObject<string[]>());
        }

        private string SyncSelectedRowIndexArrayToHiddenField(FineUI.Grid grid, FineUI.HiddenField hfSelectedIDS)
        {
            List<string> ids = GetSelectedRowIndexArrayFromHiddenField(hfSelectedIDS);
            List<int> selectedRows = new List<int>();
            if (grid.SelectedRowIndexArray != null && grid.SelectedRowIndexArray.Length > 0)
            {
                selectedRows = new List<int>(grid.SelectedRowIndexArray);
            }
            for (int i = 0, count = Math.Min(grid.PageSize, (grid.RecordCount - grid.PageIndex * grid.PageSize)); i < count; i++)
            {
                string id = grid.DataKeys[i][0].ToString();
                if (selectedRows.Contains(i))
                {
                    if (!ids.Contains(id))
                    {
                        ids.Add(id);
                    }
                }
                else
                {
                    if (ids.Contains(id))
                    {
                        ids.Remove(id);
                    }
                }
            }
            return new JArray(ids).ToString(Formatting.None);
        }

        private void UpdateSelectedRowIndexArray(FineUI.Grid grid, FineUI.HiddenField hfSelectedIDS)
        {
            List<string> ids = GetSelectedRowIndexArrayFromHiddenField(hfSelectedIDS);
            List<int> nextSelectedRowIndexArray = new List<int>();
            for (int i = 0, count = Math.Min(grid.PageSize, (grid.RecordCount - grid.PageIndex * grid.PageSize)); i < count; i++)
            {
                string id = grid.DataKeys[i][0].ToString();
                if (ids.Contains(id))
                {
                    nextSelectedRowIndexArray.Add(i);
                }
            }
            grid.SelectedRowIndexArray = nextSelectedRowIndexArray.ToArray();
        }

        #endregion

        #region 列表选择和反选时控制隐藏字段

        /// <summary>
        /// 从隐藏字段中获取选择的全部ID列表
        /// </summary>
        /// <param name="hfSelectedIDS"></param>
        /// <returns></returns>
        public List<string> GetSelectedIDsFromHiddenField(FineUI.HiddenField hfSelectedIDS)
        {
            JArray idsArray = new JArray();

            string currentIDS = hfSelectedIDS.Text.Trim();
            if (!String.IsNullOrEmpty(currentIDS))
            {
                idsArray = JArray.Parse(currentIDS);
            }
            else
            {
                idsArray = new JArray();
            }
            return new List<string>(idsArray.ToObject<string[]>());
        }

        /// <summary>
        /// 将表格当前页面选中行对应的数据同步到隐藏字段中
        /// </summary>
        /// <param name="hfSelectedIDS"></param>
        /// <param name="Grid1"></param>
        public void SyncSelectedRowIndexArrayToHiddenField(FineUI.HiddenField hfSelectedIDS, FineUI.Grid Grid1)
        {
            List<string> ids = GetSelectedIDsFromHiddenField(hfSelectedIDS);

            List<int> selectedRows = new List<int>();
            if (Grid1.SelectedRowIndexArray != null && Grid1.SelectedRowIndexArray.Length > 0)
            {
                selectedRows = new List<int>(Grid1.SelectedRowIndexArray);
            }

            if (Grid1.IsDatabasePaging)
            {
                for (int i = 0, count = Math.Min(Grid1.PageSize, (Grid1.RecordCount - Grid1.PageIndex * Grid1.PageSize)); i < count; i++)
                {
                    string id = Grid1.DataKeys[i][0].ToString();
                    if (selectedRows.Contains(i))
                    {
                        if (!ids.Contains(id))
                        {
                            ids.Add(id);
                        }
                    }
                    else
                    {
                        if (ids.Contains(id))
                        {
                            ids.Remove(id);
                        }
                    }
                }
            }
            else
            {
                int startPageIndex = Grid1.PageIndex * Grid1.PageSize;
                for (int i = startPageIndex, count = Math.Min(startPageIndex + Grid1.PageSize, Grid1.RecordCount); i < count; i++)
                {
                    string id = Grid1.DataKeys[i][0].ToString();
                    if (selectedRows.Contains(i - startPageIndex))
                    {
                        if (!ids.Contains(id))
                        {
                            ids.Add(id);
                        }
                    }
                    else
                    {
                        if (ids.Contains(id))
                        {
                            ids.Remove(id);
                        }
                    }
                }
            }

            hfSelectedIDS.Text = new JArray(ids).ToString(Formatting.None);
        }

        /// <summary>
        /// 根据隐藏字段的数据更新表格当前页面的选中行
        /// </summary>
        /// <param name="hfSelectedIDS"></param>
        /// <param name="Grid1"></param>
        public void UpdateSelectedRowIndexArray(FineUI.HiddenField hfSelectedIDS, FineUI.Grid Grid1)
        {
            List<string> ids = GetSelectedIDsFromHiddenField(hfSelectedIDS);

            List<int> nextSelectedRowIndexArray = new List<int>();
            if (Grid1.IsDatabasePaging)
            {
                for (int i = 0, count = Math.Min(Grid1.PageSize, (Grid1.RecordCount - Grid1.PageIndex * Grid1.PageSize)); i < count; i++)
                {
                    string id = Grid1.DataKeys[i][0].ToString();
                    if (ids.Contains(id))
                    {
                        nextSelectedRowIndexArray.Add(i);
                    }
                }
            }
            else
            {
                int nextStartPageIndex = Grid1.PageIndex * Grid1.PageSize;
                for (int i = nextStartPageIndex, count = Math.Min(nextStartPageIndex + Grid1.PageSize, Grid1.RecordCount); i < count; i++)
                {
                    string id = Grid1.DataKeys[i][0].ToString();
                    if (ids.Contains(id))
                    {
                        nextSelectedRowIndexArray.Add(i - nextStartPageIndex);
                    }
                }
            }
            Grid1.SelectedRowIndexArray = nextSelectedRowIndexArray.ToArray();
        }

        public string[] GetSelectedIDsFromHiddenField(string hfSelectedIDS)
        {
            JArray idsArray = new JArray();
            string currentIDS = hfSelectedIDS.Trim();
            if (!String.IsNullOrEmpty(currentIDS))
            {
                idsArray = JArray.Parse(currentIDS);
            }
            else
            {
                idsArray = new JArray();
            }
            return idsArray.ToObject<string[]>();
        }

        public string ListToString(List<string> list)
        {
            string ids = string.Empty;
            if (list.Count > 0)
            {
                foreach (string s in list)
                {
                    ids += s + ",";
                }
                ids = ids.Substring(0, ids.Length - 1);
            }
            return ids;
        }

        #endregion

        #region DataTable 查询/删除行

        // 根据行ID来获取行数据/删除行数据
        public DataRow FindRowByID(int rowID, DataTable dt)
        {
            DataTable table = dt;
            foreach (DataRow row in table.Rows)
            {
                if (Convert.ToInt32(row["Id"]) == rowID)
                {
                    return row;
                }
            }
            return null;
        }

        // 根据行ID来删除行数据
        public DataTable DeleteRowByID(int rowID, DataTable dt)
        {
            DataTable table = dt;
            DataRow found = FindRowByID(rowID, table);
            if (found != null)
            {
                table.Rows.Remove(found);
            }
            return table;
        }

        #endregion

        #region 保存选择的ID

        public void GridChooseID(FineUI.Grid GridList, bool IsEdit = false)
        {
            string idsGet = RequestUtil.GetQueryString("ids");
            List<string> ids = GetSelectedDataKeyIDs(GridList, IsEdit);
            if (ids != null && ids.Count == 1)
            {
                string id = "";
                if (ids.Count > 0) id = ids[0];
                string[] arrIds = idsGet.Split(',');
                if (arrIds.Contains(id))
                {
                    Alert.Show("不可选择重复分类数据");
                }
                else
                {
                    string selectedIds = "";
                    if (idsGet == "")
                        selectedIds = id;
                    else
                        selectedIds = idsGet + "," + id;
                    PageContext.RegisterStartupScript(ActiveWindow.GetWriteBackValueReference(id, selectedIds) + ActiveWindow.GetHidePostBackReference());
                }
            }
            else
            {
                Alert.Show("请选择一条记录");
            }
        }

        #endregion

        #region 获取页面名称
        public string GetPageName()
        {
            string url = Request.FilePath;
            if (string.IsNullOrWhiteSpace(url))
                return "";
            string pagename = url.Substring(url.LastIndexOf("/") + 1).Replace(".aspx", "");
            return pagename;
        }
        #endregion

        #region 弹出框

        /// <summary>
        /// 列表页点击弹出框
        /// </summary>
        /// <param name="page">弹出页面</param>
        /// <param name="action">操作行为</param>
        /// <param name="title">标题</param>
        /// <param name="GridList">Grid控件</param>
        /// <param name="WindowOpen">Window控件</param>
        public void OpenDialog(string page, string btn, string title, FineUI.Grid GridList, FineUI.Window WindowOpen, bool IsEdit)
        {
            if (btn == OperateType.btnNew.ToString())
            {
                string str = WindowOpen.GetShowReference(page + PageAction + btn, title);
                PageContext.RegisterStartupScript(str);
            }
            else
            {
                List<string> list = GetSelectedDataKeyIDs(GridList, IsEdit);
                if (list != null && list.Count == 1)
                {
                    string str = WindowOpen.GetShowReference(page + PageAction + btn + "&ActionID=" + list[0], title);
                    PageContext.RegisterStartupScript(str);
                }
                else
                {
                    Alert.Show("请选择一条记录后操作");
                }
            }
        }

        #endregion

        #region 窗体关闭事件
        protected void Window_Close(object sender, EventArgs e)
        {
            BindGrid();
        }
        #endregion

        #region 列表页编辑
        /// <summary>
        /// 列表页编辑必须实现
        /// </summary>
        protected virtual void SaveEdit() { }

        /// <summary>
        /// 保存编辑操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSaveEdit_Click(object sender, EventArgs e)
        {
            SaveEdit();
        }
        #endregion

        #region 数据库对应的字段类型集合
        public static Dictionary<int, Type> columnType = null;
        public static Dictionary<int, Type> ColumnType
        {
            get
            {
                if (columnType == null)
                {
                    columnType = new Dictionary<int, Type>();
                    columnType.Add(56, typeof(int));
                    columnType.Add(106, typeof(decimal));
                    columnType.Add(231, typeof(string));
                    columnType.Add(167, typeof(string));
                    columnType.Add(175, typeof(string));
                }
                return columnType;
            }
        }
        #endregion

        #region 搜索块下拉列表绑定
        /// <summary>
        /// 搜索框控件绑定值
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="drp"></param>
        /// <param name="TextField"></param>
        /// <param name="ValueField"></param>
        /// <param name="Default"></param>
        public void BindDropDownList(DataTable dt, FineUI.DropDownList drp, FineUI.ListItem li = null, string TextField = "Name", string ValueField = "ID", bool Default = true)
        {
            drp.DataSource = dt;
            drp.DataTextField = TextField;
            drp.DataValueField = ValueField;
            drp.DataBind();
            if (li != null)
            {
                drp.Items.Insert(0, li);
            }
            else
            {
                if (Default)
                {
                    drp.Items.Insert(0, new ListItem("全部", ""));
                }
            }
        }
        #endregion

        #region 弹框
        
        public void ShowAlert(string msg,bool isSuc)
        {
            if (isSuc)
            {
                Alert.Show("操作已完成", MessageBoxIcon.Information);
                PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            }
            else
            {
                Alert.Show("操作已完成", MessageBoxIcon.Warning);
            }
        }

        #endregion

        #endregion

        #region 表单页

        #region 弹出窗体时数据初始化

        /// 窗体时数据初始化
        public bool LoadData(ControlCollection ctrls, EntityBase eo)
        {
            foreach (Control control in ctrls)
            {
                if (control.HasControls())
                {
                    //递归 (重要) 否则将退出程序
                    LoadData(control.Controls, eo);
                }
                else
                {
                    if (control is ThinkTextBox && (control as ThinkTextBox).SqlField != null)
                    {
                        (control as ThinkTextBox).Text = TypeTo.ObjectToStr(eo.GetValue((control as ThinkTextBox).SqlField));
                    }
                    else if (control is ThinkTextArea && (control as ThinkTextArea).SqlField != null)
                    {
                        (control as ThinkTextArea).Text = TypeTo.ObjectToStr(eo.GetValue((control as ThinkTextArea).SqlField));
                    }
                    else if (control is ThinkTriggerBox && (control as ThinkTriggerBox).SqlField != null)
                    {
                        (control as ThinkTriggerBox).Text = TypeTo.ObjectToStr(eo.GetValue((control as ThinkTriggerBox).SqlField));
                    }
                    else if (control is ThinkDatePicker && (control as ThinkDatePicker).SqlField != null)
                    {
                        (control as ThinkDatePicker).SelectedDate = TypeTo.ObjectToDateTime(eo.GetValue((control as ThinkDatePicker).SqlField));
                    }
                    else if (control is ThinkDropDownList && (control as ThinkDropDownList).SqlField != null)
                    {
                        (control as ThinkDropDownList).SelectedValue = TypeTo.ObjectToStr(eo.GetValue((control as ThinkDropDownList).SqlField));
                    }
                    else if (control is ThinkRadioButtonList && (control as ThinkRadioButtonList).SqlField != null)
                    {
                        (control as ThinkRadioButtonList).SelectedValue = TypeTo.ObjectToStr(eo.GetValue((control as ThinkRadioButtonList).SqlField));
                    }
                    else if (control is ThinkNumberBox && (control as ThinkNumberBox).SqlField != null)
                    {
                        (control as ThinkNumberBox).Text = TypeTo.ObjectToStr(eo.GetValue((control as ThinkNumberBox).SqlField));
                    }
                    else if (control is ThinkCheckBox && (control as ThinkCheckBox).SqlField != null)
                    {
                        (control as ThinkCheckBox).Checked = TypeTo.ToBool(eo.GetValue((control as ThinkCheckBox).SqlField), false);
                    }
                    else if (control is ThinkLabel && (control as ThinkLabel).SqlField != null)
                    {
                        (control as ThinkLabel).Text = TypeTo.ObjectToStr(eo.GetValue((control as ThinkLabel).SqlField));
                    }
                }
            }
            return true;
        }
        #endregion

        #region 保存数据时的实体封装

        /// 保存数据时的实体封装
        public bool LoadEntity(ControlCollection ctrls, EntityBase eo)
        {
            foreach (Control control in ctrls)
            {
                if (control.HasControls())
                {
                    //递归 (重要) 否则将退出程序
                    LoadEntity(control.Controls, eo);
                }
                else
                {
                    if (control is ThinkTextBox && (control as ThinkTextBox).SqlField != null)
                    {
                        eo.SetProperty((control as ThinkTextBox).SqlField, (control as ThinkTextBox).Text);
                    }
                    else if (control is ThinkTextArea && (control as ThinkTextArea).SqlField != null)
                    {
                        eo.SetProperty((control as ThinkTextArea).SqlField, (control as ThinkTextArea).Text);
                    }
                    else if (control is ThinkTriggerBox && (control as ThinkTriggerBox).SqlField != null)
                    {
                        eo.SetProperty((control as ThinkTriggerBox).SqlField, (control as ThinkTriggerBox).Text);
                    }
                    else if (control is ThinkDatePicker && (control as ThinkDatePicker).SqlField != null)
                    {
                        eo.SetProperty((control as ThinkDatePicker).SqlField, (control as ThinkDatePicker).SelectedDate);
                    }
                    else if (control is ThinkDropDownList && (control as ThinkDropDownList).SqlField != null)
                    {
                        eo.SetProperty((control as ThinkDropDownList).SqlField, (control as ThinkDropDownList).SelectedValue);

                    }
                    else if (control is ThinkNumberBox && (control as ThinkNumberBox).SqlField != null)
                    {
                        eo.SetProperty((control as ThinkNumberBox).SqlField, (control as ThinkNumberBox).Text);
                    }
                    else if (control is ThinkCheckBox && (control as ThinkCheckBox).SqlField != null)
                    {
                        eo.SetProperty((control as ThinkCheckBox).SqlField, (control as ThinkCheckBox).Checked);
                    }
                    else if (control is ThinkRadioButtonList && (control as ThinkRadioButtonList).SqlField != null)
                    {
                        eo.SetProperty((control as ThinkRadioButtonList).SqlField, (control as ThinkRadioButtonList).SelectedValue);
                    }
                    else if (control is ThinkLabel && (control as ThinkLabel).SqlField != null && (control as ThinkLabel) != null)
                    {
                        eo.SetProperty((control as ThinkLabel).SqlField, (control as ThinkLabel).Text);
                    }
                }
            }
            return true;
        }
        #endregion

        #region 获取表单数据

        public T GetModelByID<T>()
        {
            ActionID = RequestUtil.GetQueryString("ActionID");
            if (!string.IsNullOrEmpty(ActionID))
                return TRuntime.GetDB().FirstOrDefault<T>("where ID=@0", ActionID);
            else
                return default(T);
        }

        #endregion

        #endregion

        #region 列表页

        #region 列表页搜索按钮触发事件

        /// <summary>
        /// 列表页搜索按钮触发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            FineUI.Button btn = sender as FineUI.Button;
            Grid GridList = btn.Parent.Parent.Parent.FindControl("GridList") as Grid;
            if (GridList != null)
            {
                GridList.PageIndex = 0;
            }
            BindGrid();
        }
        protected virtual void BindGrid() { }

        #endregion

        #region 列表页按钮触发事件

        public void OpenDialogClick(object sender, string openPage, string billName, FineUI.Grid GridList, FineUI.Window WindowOpen, bool IsEdit = false)
        {
            FineUI.Button btn = (FineUI.Button)sender;
            //按钮权限验证
            //if (Manage.CheckActionPermission(AdminLoginUser.ID, PageUrl, btn.ID) == false)
            //{
            //    return;
            //}

            if (btn.ID == OperateType.btnUpdate.ToString())
            {
                OpenDialog(openPage, btn.ID, "编辑" + billName, GridList, WindowOpen, IsEdit);
                return;
            }
            else if (btn.ID == OperateType.btnNew.ToString())
            {
                OpenDialog(openPage, btn.ID, "新增" + billName, GridList, WindowOpen, IsEdit);
                return;
            }
            else if (btn.ID == OperateType.btnView.ToString())
            {
                OpenDialog(openPage, btn.ID, "查看" + billName, GridList, WindowOpen, IsEdit);
                return;
            }
        }

        /// <summary>
        /// 列表页删除必须实现
        /// </summary>
        /// <returns></returns>
        protected virtual bool Delete()
        {
            return true;
        }

        #endregion

        #endregion
    }


    #region 按钮操作类型

    public enum OperateType
    {
        None,
        btnNew,
        btnUpdate,
        btnCheck,
        btnUnCheck,
        btnBlankout,
        btnUnBlankout,
        btnDelete,
        btnSave,
        btnView,
        btnFreeze,
        btnUnFreeze,
        btnReturn,
        btnUnReturn
    }
    #endregion
}